import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import services from '@/services/demo';
import { Button, Divider, Drawer, Input, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import ModalCard from '@/components/ModalCard';
import { queryAllNameAndTeacherId } from '@/services/demo/TeacherController';
import { URL_PREFIX } from '@/constants';
import { remove } from '@/services/demo/StudentController';

const { queryList, add, modify, removeById } =
  services.StudentController;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.StudentType) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: Partial<API.StudentType>) => {
  const hide = message.loading('正在修改');
  try {
    await modify(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

const handleRemove = async (id: string) => {
  const hide = message.loading('正在删除');
  try {
    await removeById(id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleRemoveSelected = async (selectedRows: API.StudentType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await remove({
      ids: selectedRows.map(it => it.sId) || []
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

function StudentPage() {
	const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<API.StudentType | {}>({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.StudentType>();
  const [selectedRowsState, setSelectedRows] = useState<API.StudentType[]>([]);
  const columns: ProDescriptionsItemProps<API.StudentType>[] = [
    {
      title: 'id',
      dataIndex: 'sId',
      hideInSearch: true,
      renderFormItem: () => <Input disabled/>
    },
    {
      title: '学号',
      dataIndex: 'sStudentid',
      valueType: 'text',
    },
		{
      title: '姓名',
      dataIndex: 'sName',
			valueType: 'text',
			hideInSearch: true,
    },
    {
      title: '性别',
      dataIndex: 'sSex',
			valueType: 'select',
			hideInSearch: true,
      valueEnum: {
        0: '男',
        1: '女'
      }
    },
		{
      title: '学校',
      dataIndex: 'sSchool',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '专业',
      dataIndex: 'sProfession',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '班级',
      dataIndex: 'sClass',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '班级类型',
      dataIndex: 'sClasstype',
			valueType: 'select',
			hideInSearch: true,
      valueEnum: {
        '大类班': '大类班',
        '普通班': '普通班',
        '实验班': '实验班'
      }
    },
		{
      title: '任职情况',
      dataIndex: 'sJobstatus',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '导师',
      dataIndex: 'sTutor',
			valueType: 'select',
			hideInSearch: true,
      request: async () => {
        const res = await queryAllNameAndTeacherId();
        console.log('res.data[0]',res.data[0])
        return res.data?.map((it: any) => ({
          label: `${it.tName}(工号 ${it.tTeacherid})`,
          value: it.tName,
        }))
      },
      params: {},
    },
		{
      title: '联系电话',
      dataIndex: 'sPhone',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '身份证号',
      dataIndex: 'sIdcard',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '年级',
      dataIndex: 'sGrade',
			valueType: 'text',
			hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Button type='primary'
            onClick={() => {
              setStepFormValues((_: any) => ({...record}));
              handleUpdateModalVisible(true);
            }}
          >
            修改
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
						onConfirm={async () => {
              const success = await handleRemove(record.sId)
              if (success) {
                actionRef.current?.reloadAndRest?.()
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '学生管理',
      }}
    >
      <ProTable<API.StudentType>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="sId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新建
          </Button>,
          <Button key="2" type="primary">
          <a href={URL_PREFIX + '/student/excel'} target="_blank">导出Excel</a>
        </Button>
        ]}
        request={queryList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={async () => {
              await handleRemoveSelected(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )}
      <ModalCard
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.StudentType, API.StudentType>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="sId"
          type="form"
          columns={columns}
        />
      </ModalCard>
      { stepFormValues && Object.keys(stepFormValues).length > 0 ?
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setStepFormValues({})
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.StudentType, API.StudentType>
            form={{initialValues: stepFormValues}}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({})
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="sId"
            type="form"
            columns={columns}
          />
        </ModalCard>
        :null        
      }

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.sId && (
          <ProDescriptions<API.StudentType>
            column={2}
            title={row?.sId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.sId,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
}

export default StudentPage;